package com.example.dee.controller;


import com.example.dee.config.ParamConfig;
import com.example.dee.pojo.CarData;
import com.example.dee.pojo.User;
import com.example.dee.pojo.vo.CarDataUp;
import com.example.dee.pojo.vo.ResponseJSON;
import com.example.dee.service.SysService;
import com.example.dee.threadRun.UpDataRunnable;
import com.example.dee.util.RandomUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import java.util.*;

@Controller
public class CarDataUpController {
    @Resource
    SysService sysService;
    @RequestMapping("/carDataUp")
    public String carDataUp(HttpServletRequest request, HttpServletResponse response) throws IOException {
        User sysUser = (User)request.getSession().getAttribute("sysUser");
        if(sysUser==null){
            response.getWriter().write("<script>alert('请登录');</script>");
            return "login";
        }else{
        String url= ParamConfig.URL_B;
        String[] ids = request.getParameterValues("id");
        List<CarData> carDataList = new ArrayList<>();
        String res = null;
        int bingo=0;
        if(ids!=null&&ids.length>0) {
            if(ids.length<10){
                for (String id : ids) {
                    CarData carData = sysService.selectCarData(id);
                    if (carData != null) {
                        carDataList.add(carData);
                        System.out.println(carData);
                        Map<String, Object> paramMap = new HashMap<>();
                        ObjectMapper mapper = new ObjectMapper();
                        String jsonStr = mapper.writeValueAsString(new CarDataUp(carData));
                        paramMap.put("param", jsonStr);
                        paramMap.put("command", sysService.selectCommand());
                        res = doPost(url, paramMap);
                        ResponseJSON resJson = mapper.readValue(res, ResponseJSON.class);
                        if (ParamConfig.STATE_TRUE.equals(resJson.getSubCode())) {
                            System.out.println(id);
                            System.out.println(resJson.getInfo());
                            bingo++;
                        } else {
                        }
                        //修改车辆信息上传状态与操作描述
                        sysService.updateCarDataState(id, resJson, RandomUtil.getDateFormat(new Date()));
                        sysService.addRecord(carData, resJson.getInfo(), ((User) request.getSession().getAttribute("sysUser")).getId());
                        System.out.println(resJson);
                    }
                }
                request.setAttribute("info","上传数据"+carDataList.size()+"条,"+"成功上传"+bingo+"条");
            }else {
                int sysId = ((User) request.getSession().getAttribute("sysUser")).getId();
                for (String id : ids) {
                    ParamConfig.fixedThreadPool.execute(new UpDataRunnable(id,sysId,sysService));
                }
                request.setAttribute("info","上传数据"+ids.length+"条");
            }
        }
        request.setAttribute("isDataUp","upInfo");
        carDataList = sysService.selectCarDataByUp(0,50);
        request.setAttribute("begin","50");
        request.setAttribute("carDataList",carDataList);
        return "carDataUp";
        }
    }
    @RequestMapping("/carDataUpAuto")
    public void carDataUpAuto(HttpServletRequest request,HttpServletResponse response) throws IOException {
        User sysUser = (User)request.getSession().getAttribute("sysUser");
        if(sysUser==null){
            return;
        }
        String url= ParamConfig.URL_B;
        String[] ids = request.getParameterValues("id");
        List<CarData> carDataList = new ArrayList<>();
        String res = null;
        if(ids.length>0){
            for (String id:ids) {
                ParamConfig.fixedThreadPool.execute(new UpDataRunnable(id,sysUser.getId(),sysService));
            }
        }
    }
    public static String doPost(String url,Map<String, Object> paramMap) throws JsonProcessingException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        String result = null;
        // 创建httpClient实例
        httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost(url);
        // 设置请求头
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");

        // 封装post请求参数
        if (null != paramMap && paramMap.size() > 0) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            // 通过map集成entrySet方法获取entity
            Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet();
            // 循环遍历，获取迭代器
            for (Map.Entry<String, Object> mapEntry : entrySet) {
                nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString()));
            }
            // 为httpPost设置封装好的请求参数
            try {
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        try {
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity entity = httpResponse.getEntity();

            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            ObjectMapper mapper = new ObjectMapper();
            return mapper.writeValueAsString(new ResponseJSON(ParamConfig.STATE_FALSE,"3",new Date(),"对方端口未响应"));
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
